<template>
  <view class="container">
    <uni-nav-bar 
      dark 
      :fixed="true" 
      shadow 
      status-bar 
      left-icon="arrow-left" 
      title="走访信息" 
      @clickLeft="handleBack" 
      class="nav-bar"
    />

    <view class="main-content">
      <view class="section">
        <view class="section-title">
          <view class="blue-dot"></view>
          <text class="title-text">走访信息</text>
        </view>

        <view class="form-content">
          <view class="form-item customer-input-item">
            <text class="form-label">客户信息：</text>
            <input 
              type="text" 
              placeholder="请输入客户名称/编码搜索" 
              class="form-input"
              v-model="customerInput"
              @input="handleCustomerSearch"
              @focus="handleInputFocus"
              @blur="handleInputBlur"
            />
            
            <view class="customer-table" v-if="showCustomerTable">
              <view class="table-header">
                <button class="close-btn" @click="showCustomerTable = false">
                  <uni-icons type="close" size="34rpx" color="#fff" />
                </button>
              </view>
              
              <view class="table-loading" v-if="isSearchLoading && customerInput.trim()">
                <uni-icons type="spinner" size="24rpx" color="#007aff" animation="spin" />
                <text class="loading-text">搜索中...</text>
              </view>
              
              <view class="table-content" v-else>
            
                
                <view class="table-body">
                  <view class="table-row" 
                        v-for="(customer, index) in filteredCustomers" 
                        :key="customer.partyCode + '-' + index"
                        @click="selectCustomer(customer)"
                        :class="{ 'selected-row': selectedCustomerCode === customer.partyCode }">
                    <view class="table-cell">
                      <text>{{ customer.partyName }}</text>
                      <uni-icons 
                        type="checkmark-circle" 
                        size="28rpx" 
                        color="#007aff" 
                        class="selected-icon"
                        v-if="selectedCustomerCode === customer.partyCode"
                      />
                    </view>
                  </view>
                  
                  <view class="no-data" v-if="filteredCustomers.length === 0 && !isSearchLoading && customerInput.trim()">
                    未找到匹配的客户，请重新输入
                  </view>
                  
                  <view class="no-data" v-if="!customerInput.trim() && !isSearchLoading">
                    请输入客户名称或编码进行搜索
                  </view>
                </view>
              </view>
              
              <view class="table-footer" v-if="searchPageInfo.pageTotal > 1 && !isSearchLoading">
                <!-- <text class="page-info">共 {{ searchPageInfo.total }} 条，当前第1页</text> -->
              </view>
            </view>
          </view>

          <view class="form-item">
            <text class="form-label">联系电话：</text>
            <input 
              type="number" 
              placeholder="请输入11位手机号码" 
              class="form-input"
              v-model="phone"
              maxlength="11"
            />
          </view>

          <view class="form-item">
            <text class="form-label">走访方式：</text>
            <picker 
              class="form-picker"
              mode="selector"
              :range="visitModeList"
              :range-key="'name'"
              v-model="visitModeIndex"
              @change="handleVisitModeChange"
            >
              <view class="picker-content">
                {{ visitModeList[visitModeIndex].name }}
                <uni-icons type="down" size="24rpx" color="#999" class="picker-icon" />
              </view>
            </picker>
          </view>

          <view class="form-item">
            <text class="form-label">备注：</text>
            <textarea 
              placeholder="请输入备注信息" 
              class="form-textarea"
              v-model="remark"
              auto-height
              maxlength="500"
            ></textarea>
            <text class="textarea-count">{{ remark.length }}/500</text>
          </view>

          <view class="form-item">
            <text class="form-label">图片上传：</text>
            <view class="upload-container">
              <view class="upload-btn" @click="chooseImage">
                <uni-icons type="camera" size="36rpx" color="#999" />
                <text class="upload-text">点击上传（最多5张）</text>
              </view>
              
              <view class="image-preview" v-if="imageList.length > 0">
                <view class="preview-item" 
                      v-for="(img, index) in imageList" 
                      :key="index"
                      @click="previewImage(index)">
                  <image :src="img" mode="aspectFill" class="preview-img"></image>
                  <view class="delete-img" @click.stop="deleteImage(index)">
                    <uni-icons type="close" size="24rpx" color="#fff" />
                  </view>
                </view>
              </view>
              
              <text class="upload-tip">支持JPG/PNG格式，点击图片可预览大图</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="bottom-btn-group">
      <button class="reset-btn" @click="handleReset">
        <uni-icons type="undo" size="20" color="#666" class="btn-icon" />
        重置
      </button>
      <button class="submit-btn" @click="handleSubmit" :disabled="!selectedCustomerCode || isSubmitting || !visitModeList[visitModeIndex].code">
        <uni-icons type="checkmark" size="20" color="#fff" class="btn-icon" />
        {{ isSubmitting ? '提交中...' : '提交' }}
      </button>
    </view>

    <uni-popup 
      ref="successPopup" 
      type="center" 
      :mask-click="false" 
      @close="handlePopupClose"
    >
      <view class="success-popup-container">
        <view class="popup-title">
          <uni-icons type="success" size="48rpx" color="#007aff" class="success-icon" />
          <text class="title-text">数据提交成功！</text>
        </view>
        
        <view class="popup-desc">
          <text>请选择后续操作</text>
        </view>
        
        <view class="popup-btn-group">
          <button 
            class="popup-btn return-btn" 
            @click="handleReturnToKhzf"
          >
            返回查询
          </button>
          <button 
            class="popup-btn continue-btn" 
            @click="handleContinueInput"
          >
            继续录入
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import utils from '../../common/utils'

export default {
  data() {
    return {
      customerInput: '',
      selectedCustomerCode: '',
      selectedCustomer: null,
      phone: '',
      remark: '',
      imageList: [],
      visitModeList: [
        { code: '1', name: '电话' },
        { code: '2', name: '微信' },
        { code: '3', name: '上门' }
      ],
      visitModeIndex: 0,
      filteredCustomers: [],
      showCustomerTable: false,
      isSearchLoading: false,
      searchTimer: null,
      searchPageInfo: {
        total: 0,
        curPage: 1,
        pageTotal: 0,
        pageSize: 10
      },
      isSubmitting: false,
      isUnmounted: false
    };
  },
  methods: {
    handleBack() {
      uni.navigateTo({
      	url:'/pages/khzf/khzf'
      })
    },
    handleReset() {
      this.customerInput = '';
      this.selectedCustomerCode = '';
      this.selectedCustomer = null;
      this.phone = '';
      this.remark = '';
      this.imageList = [];
      this.filteredCustomers = [];
      this.visitModeIndex = 0;
      uni.showToast({ title: '表单已重置', icon: 'none', duration: 1200 });
    },
    handleSubmit() {
      if (!this.selectedCustomerCode) {
        uni.showToast({ title: '请先选择客户', icon: 'none' });
        return;
      }
      if (!this.phone) {
        uni.showToast({ title: '请输入联系电话', icon: 'none' });
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        uni.showToast({ title: '请输入正确的11位手机号', icon: 'none' });
        return;
      }
      if (!this.visitModeList[this.visitModeIndex]?.code) {
        uni.showToast({ title: '请选择有效的走访方式', icon: 'none' });
        return;
      }
      this.isSubmitting = true;
      this.$utils.showLoading("数据提交中...");
      const files = this.imageList.map((filePath, index) => {
        return {
          name: 'wj',
          uri: filePath
        };
      });
      let data = {
        customerName: this.customerInput,
        customerCode: this.selectedCustomerCode,
        phone: this.phone,
        visitMode: this.visitModeList[this.visitModeIndex].code,
        remark: this.remark,
        isApp: '1',
        lx:'0',
        timestamp: this.$utils.getTimestamp()
      };
      let userInfo = uni.getStorageSync("userInfo");
      let enData = this.$utils.encrypt(JSON.stringify(data), userInfo.aesKey, userInfo.aesIv);
      let postData = {
        data: "" + enData + ""
      };
      (async () => {
        try {
          var res;
          if (files.length > 0) {
            res = await this.$myRequest.post_file_token(getApp().globalData.khzf + "/save", files, postData);
          } else {
            res = await this.$myRequest.get_token(getApp().globalData.khzf + "/save", enData);
          }
          this.$utils.hideLoading();
          this.isSubmitting = false;
          if (res.code == 200) {
            this.$refs.successPopup.open();
          } else {
            this.$utils.toast("数据提交失败！" + (res.msg || ''));
          }
        } catch (e) {
          this.$utils.hideLoading();
          this.isSubmitting = false;
          this.$utils.toast("数据提交失败！" + e.message);
        }
      })();
    },
    handleVisitModeChange(e) {
      this.visitModeIndex = e.detail.value;
    },
    chooseImage() {
      const maxCount = 5 - this.imageList.length;
      if (maxCount <= 0) {
        uni.showToast({ title: '最多只能上传5张图片', icon: 'none' });
        return;
      }
      uni.chooseImage({
        count: maxCount,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          if (this.isUnmounted) return;
          this.imageList = this.imageList.concat(res.tempFilePaths);
        }
      });
    },
    deleteImage(index) {
      this.imageList.splice(index, 1);
      uni.showToast({ title: '图片已删除', icon: 'none', duration: 1000 });
    },
    previewImage(currentIndex) {
      uni.previewImage({
        current: currentIndex,
        urls: this.imageList,
        loop: true,
        indicator: 'number'
      });
    },
    handleCustomerSearch(e) {
      const value = e.detail.value.trim();
      if (this.searchTimer) clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(async () => {
        if (this.isUnmounted) return;
        this.showCustomerTable = true;
        if (!value) {
          this.filteredCustomers = [];
          this.isSearchLoading = false;
          return;
        }
        this.isSearchLoading = true;
        try {
          const timestamp = this.$utils.getTimestamp();
          const userInfo = uni.getStorageSync("userInfo");
          const requestParams = {
            timestamp,
            cxmc: value,
            curpage: 1,
            pagesize: 15
          };
          const enData = this.$utils.encrypt(
            JSON.stringify(requestParams),
            userInfo.aesKey,
            userInfo.aesIv
          );
          const res = await this.$myRequest.post_token(
            getApp().globalData.khzf + "/khcx",
            { data: enData + "" }
          );
          if (this.isUnmounted) return;
          if (res.code === 200) {
            const decryptedData = JSON.parse(utils.decrypt(
              res.data,
              userInfo.aesKey,
              userInfo.aesIv
            ));
            this.searchPageInfo = decryptedData.pageInfo || {
              total: 0,
              curPage: 1,
              pageTotal: 0,
              pageSize: 10
            };
            this.filteredCustomers = (decryptedData.listInfo || [])
              .filter(item => item.partyName && item.partyCode)
              .sort((a, b) => a.partyName.localeCompare(b.partyName, 'zh-CN'));
          } else {
            this.filteredCustomers = [];
            this.$utils.toast(`搜索失败！错误码[${res.code}]`);
          }
        } catch (e) {
          this.filteredCustomers = [];
          console.error("搜索异常：", e);
          this.$utils.toast("搜索失败！" + (e.message || "网络异常"));
        } finally {
          if (this.isUnmounted) return;
          this.isSearchLoading = false;
        }
      }, 300);
    },
    selectCustomer(customer) {
      this.selectedCustomer = customer;
      this.customerInput = customer.partyName;
      this.selectedCustomerCode = customer.partyCode;
      this.phone = customer.contactPhone || '';
      this.showCustomerTable = false;
    },
    handleInputFocus() {
      this.showCustomerTable = true;
      if (this.customerInput.trim() && !this.isSearchLoading) {
        this.handleCustomerSearch({ detail: { value: this.customerInput } });
      }
    },
    handleInputBlur() {
      setTimeout(() => {
        // 核心逻辑：如果输入内容与选中客户名称不一致，清空选中信息
        if (this.selectedCustomer && this.customerInput !== this.selectedCustomer.partyName) {
          this.selectedCustomerCode = '';
          this.selectedCustomer = null;
          this.phone = '';
        }
        if (this.showCustomerTable) {
          this.showCustomerTable = false;
        }
      }, 200);
    },
    handleReturnToKhzf() {
      this.$refs.successPopup.close();
      uni.switchTab({
        url: '/pages/khzf/khzf',
        fail: (err) => {
          uni.redirectTo({
            url: '/pages/khzf/khzf',
            fail: (err2) => {
              console.error('跳转khzf页面失败：', err2);
              this.handleBack();
            }
          });
        }
      });
    },
    handleContinueInput() {
      this.$refs.successPopup.close();
      this.handleReset();
      this.showCustomerTable = false;
      this.filteredCustomers = [];
      this.isSearchLoading = false;
      uni.showToast({
        title: '已清空信息，可继续录入',
        icon: 'none',
        duration: 1500
      });
    },
    handlePopupClose() {
    }
  },
  beforeUnmount() {
    this.isUnmounted = true;
    if (this.searchTimer) clearTimeout(this.searchTimer);
  }
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  position: relative;
}
.nav-bar {
  border-radius: 0 !important;
  height: 44px !important;
  background-color: #fff !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05) !important;
}
.main-content {
  flex: 1;
  padding: 10px 20rpx 120rpx;
  box-sizing: border-box;
  overflow-y: auto;
}
.section {
  width: 100%;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-sizing: border-box;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}
.section-title {
  display: flex;
  align-items: center;
  height: 40rpx;
  margin-bottom: 30rpx;
}
.blue-dot {
  width: 12rpx;
  height: 36rpx;
  background-color: #007aff;
  border-radius: 2rpx;
  margin-right: 12rpx;
}
.title-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  line-height: 40rpx;
}
.form-content {
  width: 100%;
}
.form-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 35rpx;
  box-sizing: border-box;
}
.form-item.customer-input-item {
  position: relative;
}
.form-label {
  font-size: 30rpx;
  color: #666;
  margin-bottom: 18rpx;
  line-height: 1.2;
}
.form-input {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 30rpx;
  color: #333;
  background-color: #fff;
  box-sizing: border-box;
}
.form-input::placeholder {
  color: #b3b3b3;
  font-size: 28rpx;
}
.form-picker {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 30rpx;
  color: #333;
  background-color: #fff;
  box-sizing: border-box;
}
.picker-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100%;
}
.picker-icon {
  margin-left: 10rpx;
}
.form-textarea {
  width: 100%;
  min-height: 160rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 30rpx;
  color: #333;
  background-color: #fff;
  box-sizing: border-box;
  line-height: 1.5;
  resize: none;
}
.form-textarea::placeholder {
  color: #b3b3b3;
  font-size: 28rpx;
}
.textarea-count {
  align-self: flex-end;
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #999;
}
.upload-container {
  width: 100%;
}
.upload-btn {
  width: 100%;
  height: 120rpx;
  border: 1px dashed #ddd;
  border-radius: 8rpx;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
}
.upload-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 10rpx;
}
.image-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  margin-bottom: 15rpx;
  width: 100%;
}
.preview-item {
  width: calc((100% - 30rpx) / 3);
  padding-bottom: calc((100% - 30rpx) / 3 * 0.8);
  position: relative;
  border-radius: 8rpx;
  overflow: hidden;
  border: 1px solid #eee;
  box-sizing: border-box;
}
.preview-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
.delete-img {
  position: absolute;
  top: 0;
  right: 0;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}
.upload-tip {
  font-size: 24rpx;
  color: #999;
  line-height: 1.4;
}
.customer-table {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  width: 100%;
  max-height: 450rpx;
  background-color: #fff;
  border-radius: 8rpx;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.table-header {
  height: 50rpx;
  padding: 0 15rpx;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border-bottom: 1px solid #eee;
  background-color: #fafafa;
}
.close-btn {
  height: 36rpx;
  width: 36rpx;
  padding: 0;
  background-color: #007aff;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.table-loading {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  font-size: 26rpx;
  color: #007aff;
}
.table-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.table-row {
  display: flex;
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
}
.header-row {
  background-color: #f5f5f5;
  font-weight: 500;
}
.table-row:not(.header-row):active {
  background-color: #f0f7ff;
}
.selected-row {
  background-color: #e8f4ff;
}
.table-cell {
  width: 100%;
  padding: 0 15rpx;
  font-size: 26rpx;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  box-sizing: border-box;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.selected-icon {
  margin-left: 10rpx;
}
.table-body {
  flex: 1;
  overflow-y: auto;
}
.no-data {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
  color: #999;
  height: 90rpx;
  line-height: 90rpx;
}
.table-footer {
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #999;
  border-top: 1px solid #eee;
}
.bottom-btn-group {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 110rpx;
  background-color: #fff;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  box-sizing: border-box;
  z-index: 99;
}
.reset-btn, .submit-btn {
  width: 46%;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}
.reset-btn {
  border: 1px solid #ddd;
  color: #666;
  background-color: #fff;
}
.submit-btn {
  background-color: #007aff;
  color: #fff;
  border: none;
}
.submit-btn:disabled {
  background-color: #ccc;
  color: #fff;
  opacity: 0.7;
}
.btn-icon {
  margin-right: 10rpx;
}
.success-popup-container {
  width: 600rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx 20rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 30rpx;
}
.popup-title {
  display: flex;
  align-items: center;
  gap: 15rpx;
}
.success-icon {
  font-weight: bold;
}
.popup-desc {
  font-size: 28rpx;
  color: #666;
  text-align: center;
}
.popup-btn-group {
  width: 100%;
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
  margin-top: 10rpx;
}
.popup-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: 500;
}
.return-btn {
  background-color: #fff;
  border: 1px solid #007aff;
  color: #007aff;
}
.continue-btn {
  background-color: #007aff;
  color: #fff;
  border: none;
}
.main-content::-webkit-scrollbar,
.table-body::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
.main-content::-webkit-scrollbar-thumb,
.table-body::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 0;
}
</style>
